package com.ipad.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ipad.R;
import com.ipad.net.ApiClient;
import com.ipad.net.entity.LoginEntity;
import com.ipad.net.entity.UpdateEntity;
import com.ipad.net.entity.UserInfo;
import com.ipad.net.entity.WarehouseList;
import com.ipad.net.presenter.CheckVersionPresenter;
import com.ipad.net.presenter.UserPresent;
import com.ipad.net.view.ICheckVersionView;
import com.ipad.net.view.IUserView;
import com.ipad.ui.BaseActivity;
import com.ipad.ui_operation.OperationMainActivity;
import com.ipad.utils.ActivityStack;
import com.ipad.utils.SharePerenceUtils;
import com.ipad.utils.ToasUtils;
import com.ipad.view.dialog.SignDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import pub.devrel.easypermissions.EasyPermissions;

public class LoginActivity extends BaseActivity implements IUserView, ICheckVersionView,EasyPermissions.PermissionCallbacks {
    @BindView(R.id.index_password)
    EditText index_password;
    @BindView(R.id.index_username)
    EditText index_username;
    @BindView(R.id.index_login)
    Button index_login;
    private String TAG = "login";

    String userName = "";
    String password = "";
    UserPresent userPresent;
    private CheckVersionPresenter checkVersionPresenter;
    ProgressBar mProgress;
    TextView alert_tv;
    String[] url = new String[1];
    private int[] progress = new int[1];
    private static final String savePath = "/sdcard/updatedemo/";// 保存apk的文件夹
    private static final String saveFileName = savePath + "update_pda.apk";

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        //设置密码框
        final boolean[] showing_pwd = {false};
        final Drawable open = getResources().getDrawable(R.drawable.eye_open);
        open.setBounds(0, 0, open.getIntrinsicWidth(), open.getIntrinsicHeight());

        final Drawable close = getResources().getDrawable(R.drawable.eye_close);
        close.setBounds(0, 0, close.getIntrinsicWidth(), close.getIntrinsicHeight());
        String sp_userName = SharePerenceUtils.getUserName(this);
        String sp_password = SharePerenceUtils.getPassword(this);

        if (sp_userName != null && !sp_userName.equals("")) {
            index_username.setText(sp_userName);
        }

        if (sp_password != null && !sp_password.equals("")) {
            index_password.setText(sp_password);
        }


        index_password.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Drawable drawable = index_password.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null)
                    return false;
                //如果不是按下事件，不再处理

                //left
                if (event.getX() >
                        index_password.getMeasuredWidth() - index_password.getPaddingRight() - drawable.getIntrinsicWidth()) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        //按下动作处理
                        if (showing_pwd[0]) {
                            showing_pwd[0] = false;

                        } else {
                            showing_pwd[0] = true;

                        }
                        return false;
                    }
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        //抬起动作处理
                        if (!showing_pwd[0]) {
                            index_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                            index_password.setCompoundDrawables(null, null, close, null);
                        } else {
                            index_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                            index_password.setCompoundDrawables(null, null, open, null);
                        }
                        index_password.setSelection(index_password.getText().toString().length());
                        return false;
                    }
                }
                return false;
            }
        });
//登录
        index_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (index_username.getText().toString() == null || index_username.getText().toString().equals("")) {
                    ToasUtils.getToast(getResources().getString(R.string.empty_name), LoginActivity.this);
                    return;
                }
                if (index_password.getText().toString() == null || index_password.getText().toString().equals("")) {
                    ToasUtils.getToast(getResources().getString(R.string.empty_pwd), LoginActivity.this);
                    return;
                }
                LoginActivity.this.userName = index_username.getText().toString();
                password = index_password.getText().toString();
                login(LoginActivity.this.userName, password);
            }
        });

    }

    public void login(String userName, String pwd) {
        if (userPresent != null) {
            userPresent.login(userName, pwd);
        }
    }

    @Override
    public void initData() {
        String[] perms = {
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA

        };
//        if (EasyPermissions.hasPermissions(this,perms)){
//            update();
//        }else {
//            EasyPermissions.requestPermissions(this,"请添加“应用更新”使用权限",0x11,perms);
//        }

        userPresent = new UserPresent();
        userPresent.attchView(this);

    }

    @Override
    public void setToolbar() {

    }

    @Override
    public void stopLoading() {
        super.dismissDialog();
    }

    @Override
    public void loading(String msg) {
        super.showDialog(msg);
        loadingDialog.setInf(msg);
    }

    @Override
    public void error(String msg) {
        ToasUtils.getToast(msg, this);
    }

    @Override
    public void getUserInfo(UserInfo info) {

    }

    @Override
    public void getUserError() {

    }

    @Override
    public void login(LoginEntity loginEntity) {
        Log.e(TAG, "login: " + 1);
        if (loginEntity != null) {
            if (loginEntity.getCode().equals("200")) {

                SharePerenceUtils.setToken(this, loginEntity.getToken());
                SharePerenceUtils.setPassword(this, userName, password);
                if (getApplication().getPackageName().equals("com.ipad")){
                    Intent intent = new Intent(this, com.ipad.ui.activity.IndexActivity.class);
                    startActivity(intent);
                }else if (getApplication().getPackageName().equals("com.ipad.opearation")){
                    Intent intent = new Intent(this, OperationMainActivity.class);
                    startActivity(intent);
                }
                finish();
                ActivityStack.getInstance().removeActivity(this);
            } else {
                ToasUtils.getToast(loginEntity.getMessage(), this);
            }
        }
    }

    @Override
    public void getWarehouseList(WarehouseList warehouseList) {

    }

    public void update() {
        String[] permissions = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        };

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> mPermissionList = new ArrayList<>();

            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);
                }
            }
            if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了

//                checkVersion();
            } else {//请求权限方法
                String[] permissions2 = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
                ActivityCompat.requestPermissions(this, permissions2, 0x11);
            }

        } else {
//            checkVersion();
        }

    }

    public void checkVersion() {
        checkVersionPresenter = new CheckVersionPresenter();
        checkVersionPresenter.attchView(this);
        PackageManager packageManager = getPackageManager();
        PackageInfo packageInfo = null;
        int versionCode = 1;
        String version_name = "";
        try {
            packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            versionCode = packageInfo.versionCode;
            version_name = packageInfo.versionName;
//            app_version.setText("版本号: "+version_name);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            versionCode = 0;
        }

        checkVersionPresenter.checkVersion(ApiClient.client_type, versionCode + "");


    }

    @Override
    public void checkVersion(UpdateEntity updateEntity) {
        if (updateEntity != null) {
            if (updateEntity.getCode() == 200) {
                url[0] = updateEntity.getData().getUpgrade_url();
                showNoticeDialog(updateEntity.getMessage());
            }
        }
    }

    @Override
    public void getVersionFail() {

    }


    private void showNoticeDialog(String msg) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
                this);
        builder.setTitle("软件版本更新");
        builder.setMessage(msg);
        builder.setPositiveButton("下载", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                showDownloadDialog();
            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.setCancelable(false);
        alertDialog.show();


    }

    AlertDialog loading;

    protected void showDownloadDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        // builder.setTitle("软件版本更新");
        final LayoutInflater inflater = getLayoutInflater();
        View v = inflater.inflate(R.layout.progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.pro_alert);
        alert_tv = (TextView) v.findViewById(R.id.alert_tv);
        builder.setView(v);
        builder.setTitle("更新中...");
        loading = builder.create();
//        loading.setCancelable(false);
        loading.show();
        UpdateApp updateApp = new UpdateApp();
        updateApp.execute(url);
    }

    protected void installApk(String saveFileName) {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri contentUri = FileProvider.getUriForFile(this, "jinzhou.com.jinzhoumodle.fileProvider", apkfile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        if (this.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            this.startActivity(intent);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        update();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ToasUtils.getToast("请打开\"访问内存权限\"",this);
    }


    private class UpdateApp extends AsyncTask<String, Integer, Boolean> {
        boolean isLoading = true;

        @Override
        protected Boolean doInBackground(String... params) {
            String apkUrl = params[0];
            URL url = null;
            try {
                url = new URL(apkUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(30000);
                conn.connect();
                int length = conn.getContentLength();
                InputStream ins = conn.getInputStream();
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdir();
                }
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream outStream = new FileOutputStream(ApkFile);
                int count = 0;
                byte buf[] = new byte[1024];
                do {
                    int numread = ins.read(buf);
                    if (numread != -1) {
                        count += numread;
                    }
                    progress[0] = (int) (((float) count / length) * 100);
                    // Log.e("download", "run: "+progress );
                    // 下载进度
                    publishProgress(progress[0]);
                    if (numread != -1) {
                        outStream.write(buf, 0, numread);
                    }
                } while (isLoading);
                outStream.close();
                ins.close();

            } catch (Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToasUtils.getToast("下载失败", LoginActivity.this);
                    }
                });
            }


            return true;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            isLoading = true;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            mProgress.setProgress(values[0]);
            alert_tv.setText(values[0] + "%");
            if (values[0] == 100) {
                isLoading = false;
            }
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
//            if (numread <= 0) {
            // 下载完成通知安装
            loading.dismiss();
            installApk(saveFileName);
//                break;
//            }
        }


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }


}
